package com.example.triprec.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.triprec.R;
import com.example.triprec.common.Result;
import com.example.triprec.dao.UserDao;
import com.example.triprec.entity.User;
import com.example.triprec.utils.CurrentUserUtils;

public class LoginActivity extends AppCompatActivity {

    private static final String PREFS_NAME = "login_prefs";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_REMEMBER = "remember";
    private static final int REQUEST_CODE_REGISTER = 1001;
    
    private EditText etUsername;
    private EditText etPassword;
    private CheckBox cbRemember;
    private Button btnLogin;
    private TextView tvRegister;
    private SharedPreferences loginPrefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initViews();
        setupListeners();

        // 加载保存的登录信息
        loadSavedLoginInfo();
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        cbRemember = findViewById(R.id.cb_remember);
        btnLogin = findViewById(R.id.btn_login);
        tvRegister = findViewById(R.id.tv_register);

        // 初始化SharedPreferences
        loginPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    }

    private void loadSavedLoginInfo() {
        boolean isRemember = loginPrefs.getBoolean(KEY_REMEMBER, false);
        if (isRemember) {
            String username = loginPrefs.getString(KEY_USERNAME, "");
            String password = loginPrefs.getString(KEY_PASSWORD, "");

            // 填充保存的用户名和密码
            etUsername.setText(username);
            etPassword.setText(password);
            cbRemember.setChecked(true);
        }
    }

    private void setupListeners() {
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doLogin();
            }
        });

        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivityForResult(intent, REQUEST_CODE_REGISTER);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_REGISTER && resultCode == RESULT_OK && data != null) {
            String username = data.getStringExtra("username");
            String password = data.getStringExtra("password");

            if (username != null && password != null) {
                etUsername.setText(username);
                etPassword.setText(password);
            }
        }
    }

    private void doLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        boolean isRemember = cbRemember.isChecked();

        // UI层参数检查
        if (username.isEmpty()) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            etPassword.setError("请输入密码");
            etPassword.requestFocus();
            return;
        }

        // 使用UserDao进行登录
        Result<User> result = UserDao.login(username, password);

        // 显示登录结果提示
        Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();

        // 如果登录成功，保存登录状态并跳转到主页面
        if (result.isSuccess()) {
            // 设置当前用户
            CurrentUserUtils.setCurrentUser(result.getData().getId());
            saveLoginStatus(username, password, isRemember);
            navigateToMainActivity();
        }
    }

    private void saveLoginStatus(String username, String password, boolean isRemember) {
        SharedPreferences.Editor editor = loginPrefs.edit();
        editor.putString(KEY_USERNAME, username);

        // 根据是否勾选"记住我"来决定是否保存密码
        if (isRemember) {
            editor.putString(KEY_PASSWORD, password);
        } else {
            editor.remove(KEY_PASSWORD);
        }

        editor.putBoolean(KEY_REMEMBER, isRemember);
        editor.apply();
    }

    private void navigateToMainActivity() {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
} 